package com.efounder.widget;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.ospmobilelib.R;
import com.efounder.util.StorageUtil;
import com.pansoft.resmanager.ResFileManager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

public class MenuGridView_new extends GridView {
	private Context context;

	private ArrayList<Object> data_list;

	ExtEdgeListLayoutBroadcast extEdgeListLayoutBroadcast;
	private StorageUtil storageUtil;
	private GridAdapter gridAdapter;

	ArrayList<HashMap<String, Object>> listmap;

	ArrayList<Object> extEdgeMenus;
	Boolean isAllSelect = false;
	ViewTagInterface viewTagInterFace = null;
	int numBeforeSave;

	public ViewTagInterface getViewTagInterFace() {
		return viewTagInterFace;
	}

	public void setViewTagInterFace(ViewTagInterface viewTagInterFace) {
		this.viewTagInterFace = viewTagInterFace;
	}

	public MenuGridView_new(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;

	}

	public MenuGridView_new(Context context) {
		super(context);
		this.context = context;

		/*
		 * // 注册广播类 extEdgeListLayoutBroadcast = new
		 * ExtEdgeListLayoutBroadcast(); // 注册intentFilter IntentFilter filter =
		 * new IntentFilter(); filter.addAction("uiChange");
		 * BroadCastutil.getinstance().addbroadCast(extEdgeListLayoutBroadcast);
		 * // 注册filter，连接broadcastSaveFile
		 * this.context.registerReceiver(extEdgeListLayoutBroadcast, filter);
		 */
	}

	public void setList(ArrayList<Object> extEdgeMenus, int num) {
		numBeforeSave = num;
		if (extEdgeMenus != null) {
			this.extEdgeMenus = extEdgeMenus;
			gridAdapter = new GridAdapter(context, this.extEdgeMenus);
			this.setAdapter(gridAdapter);
			gridAdapter.notifyDataSetChanged();
			this.setSelector(R.color.transparent);
		}
	}

	public class GridAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private Context mContext;
		LinearLayout.LayoutParams params;
		ArrayList<Object> listmap;

		@SuppressLint("NewApi")
		public GridAdapter(Context context, ArrayList<Object> listmap) {
			this.listmap = listmap;
			mContext = context;
			mInflater = LayoutInflater.from(context);

			params = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			params.gravity = Gravity.CENTER;
		}

		public int getCount() {
			return listmap.size() - 1;
		}

		public Object getItem(int position) {
			return listmap.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			final ItemViewTag viewTag;
			storageUtil = new StorageUtil(mContext, "storage");
			if (convertView == null) {
				convertView = mInflater
						.inflate(R.layout.menugriditem_new, null);

				// construct an item tag
				viewTag = new ItemViewTag(
						(ImageView) convertView.findViewById(R.id.image2),
						(TextView) convertView.findViewById(R.id.text2),
						(ImageView) convertView
								.findViewById(R.id.grid_selected));
				// (ImageView) convertView.findViewById(R.id.allselect),
				// (Button) convertView.findViewById(R.id.gridsavebutton));
				convertView.setTag(viewTag);
			} else {
				viewTag = (ItemViewTag) convertView.getTag();
			}

			// set name
			viewTag.mName.setText(((StubObject) listmap.get(position))
					.getString("caption", "").toString());

			ApplicationInfo appInfo = context.getApplicationInfo();

			String menuIcon = (String) ((StubObject) listmap.get(position))
					.getString("menuIcon", "");
			menuIcon = ResFileManager.IMAGE_DIR + "/" + menuIcon;
			File file = new File(menuIcon);
			Bitmap bm = null;
			if (file.exists()) {
				bm = BitmapFactory.decodeFile(menuIcon);
			}

			else if (bm == null) {
				// yqs修改
				/*
				 int resID = context.getResources().getIdentifier(
				  "iframe_icon_refresh", "drawable", appInfo.packageName);
				 */
				int resID = context.getResources().getIdentifier("ic_blank_white",
						"drawable", appInfo.packageName);
				bm = BitmapFactory
						.decodeResource(context.getResources(), resID);
			}
			viewTag.mIcon.setImageBitmap(bm);

			if ((Boolean) ((StubObject) listmap.get(position)).getBoolean(
					"ischecked", false)) {

				viewTag.selected.setBackgroundResource(R.drawable.gridselected);

			}
			viewTag.selected.setOnClickListener(new OnClickListener() {

				@SuppressLint("NewApi")
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if ((Boolean) ((StubObject) listmap.get(position))
							.getBoolean("ischecked", false)) {

						((ImageView) v)
								.setBackgroundResource(R.drawable.gridnoselected);
						((StubObject) listmap.get(position)).setBoolean(
								"ischecked", false);
						((StubObject) extEdgeMenus.get(position)).setBoolean(
								"ischecked", false);

						gridAdapter.notifyDataSetChanged();
						storageUtil.putBoolean("isAllSelected", false);
						storageUtil.commit();
						numBeforeSave--;

					} else {
						((ImageView) v)
								.setBackgroundResource(R.drawable.gridselected);
						((StubObject) listmap.get(position)).setBoolean(
								"ischecked", true);
						((StubObject) extEdgeMenus.get(position)).setBoolean(
								"ischecked", true);
						numBeforeSave++;

					}
					// FilesOperationDataUtil.clearFileData(mContext);
					// FilesOperationDataUtil.createFile(mContext,
					// extEdgeMenus);
					// sendBroadCast();
					viewTagInterFace.viewtagClick(numBeforeSave);
				}
			});

			return convertView;
		}

		class ItemViewTag {
			protected ImageView mIcon;
			protected TextView mName;
			protected ImageView selected;

			// protected ImageView allSelected;
			// protected Button saveButton;

			/**
			 * The constructor to construct a navigation view tag
			 * 
			 * @param name
			 *            the name view of the item

			 *            the size view of the item
			 * @param icon
			 *            the icon view of the item
			 */
			public ItemViewTag(ImageView icon, TextView name, ImageView selected) {
				this.mName = name;
				this.mIcon = icon;
				this.selected = selected;
				// this.allSelected = allSelected;
				// this.saveButton = saveButton;
			}
		}
	}

	public void refresh() {
	//	data_list = FilesOperationDataUtil.readFile(context);

		gridAdapter.notifyDataSetChanged();
	}

	/*
	 * 文件保存成功后发送广播
	 */
	public void sendBroadCast() {

		String ACTION = "CommonGridViewuiChange";
		Intent intent = new Intent();
		intent.putExtra("name", "buttonclick");
		intent.setAction(ACTION);
		// 普通广播
		context.sendBroadcast(intent);
	}

	public class ExtEdgeListLayoutBroadcast extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			String name = intent.getStringExtra("name");

			if ("del".equals(name)) {
				refresh();
			}
		}
	}

	// load回调
	public interface ViewTagInterface {
		public void viewtagClick(int num);

	}

}
